package com.person.blog.controller;

import javax.servlet.http.HttpServletRequest;

import com.person.blog.mapper.UserMapper;
import com.person.blog.pojo.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 用户请求处理类
 */
@Controller
public class AccountController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 默认显示首页请求
     * @return 主页名称
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 注册页面请求
     */
    @GetMapping("/register")
    public String register() {
        // Spring 会自动转换为对应的 register.jsp
        return "register";
    }

    /**
     * 注册处理请求，用于 AJAX 的 POST 请求
     * @param username 用户名
     * @param password1 密码
     * @param password2 确认密码
     * @return 操作信息
     */
    @PostMapping(path = "/do_register", produces = "text/plain; charset=utf-8")
    @ResponseBody
    public String doRegister(@RequestParam String username, @RequestParam String password1, @RequestParam String password2) {
        if (! password1.equals(password2)) {
            return "两次密码不同";
        }
        UserEntity userEntity = userMapper.findUserByUsername(username);
        if (userEntity != null) {
            return "此用户名已经被注册";
        }

        userMapper.addUser(username, password1, System.currentTimeMillis());
        return "注册成功";
    }

    /**
     * 进去登入页面请求
     * @return 登录页面名称
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * 用户登录处理请求，用于 AJAX 的 POST 请求
     * @param request HttpServletRequest对象
     * @param username 用户名
     * @param password 密码
     * @return 返回信息
     */
    @PostMapping(path = "/do_login", produces = "text/plain; charset=utf-8")
    @ResponseBody
    public String doLogin(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
        UserEntity userEntity = userMapper.findUserByUsernameAndPassword(username, password);
        if (userEntity == null) {
            return "用户名或密码错误";
        }

        // 添加 session
        request.getSession().setAttribute("username", username);
        return "登入成功";
    }

    /**
     * 处理退出操作，移除 session
     * @param request HttpServletRequest对象
     * @return 跳转信息
     */
    @GetMapping(path = "/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("username");
        // 跳转到首页
        return "redirect:/";
    }
}